package app

import (
	"encoding/json"
	"gitee.com/zhucheer/orange/cfg"
	"gitee.com/zhucheer/orange/internal"
	"gitee.com/zhucheer/orange/logger"
	"gitee.com/zhucheer/orange/session"
	"net/http"
)

// 注册session
func sessionInit() {
	sessionOpen := cfg.GetBool("app.session.isOpen", cfg.ConfigDef.GetBool("app.session.isOpen"))
	appKey := internal.GetAppKey()
	if sessionOpen == false {
		internal.ConsoleLog("session not open")
		return
	}

	sessionTimeOut := cfg.GetInt64("app.session.timeout", cfg.ConfigDef.GetInt64("app.session.timeout"))
	sessionConfig := map[string]interface{}{
		"name":         "orange_sess",
		"blockKey":     appKey[:16],
		"securityName": "orange_hmac",
		"securityKey":  appKey,
	}
	sessionConfigJson, _ := json.Marshal(sessionConfig)

	// cookieName 存储session的cookie名称
	// blockKey AES加密session秘钥 16,24,32长度
	// securityName 参与混淆加密字符
	// securityKey hmac加密秘钥
	var config = &session.ManagerConfig{
		EnableSetCookie: true,
		CookieName:      "orange_sessionid",
		Gclifetime:      sessionTimeOut,
		DisableHTTPOnly: true,
		ProviderConfig:  string(sessionConfigJson),
	}
	sessionDriver := cfg.GetString("app.session.driver", cfg.ConfigDef.GetString("app.session.driver"))
	err := session.NewSession(sessionDriver, config)
	if err != nil {
		logger.Error("session init error %v", err)
	}

	internal.ConsoleLog("session started")
}

// 启动session
func sessioinStart(writer http.ResponseWriter, request *http.Request) session.Store {
	sessionOpen := cfg.GetBool("app.session.isOpen", cfg.ConfigDef.GetBool("app.session.isOpen"))
	blankSession := &session.BlankSessionStore{}

	if sessionOpen == false {
		return blankSession
	}
	sessHandler, sessErr := session.SessionStart(writer, request)

	if sessErr != nil && sessHandler == nil {
		logger.Error("session start error:%v", sessErr)
		return blankSession
	}

	if sessErr != nil {
		logger.Warning("session start warning:%v", sessErr)
	}
	if sessHandler == nil {
		return blankSession
	}

	return sessHandler
}
